<!DOCTYPE html>
<html lang="zh-cn">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JS010-随机颜色案例</title>
</head>
<style>
  * {
    padding: 0;
    margin: 0;
  }

  .box-container {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    justify-content: center;
    align-items: center;
    width: 100vw;
    height: 100vh;
    background-color: #777;
  }

  .random-color-box {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 150px;
    height: 100px;
    border: 2px solid black;
    overflow: hidden;
  }

  p {
    text-wrap: nowrap;
    text-align: center;
    background-color: rgba(255, 255, 255, 0.5);
  }
</style>

<body>
  <script>
    document.writeln('<div class="box-container">')
    for (let i = 0; i < 8; i++) {
      const randomRgb = getRandomRgb()
      const colorRgb = getColorRgb(randomRgb)
      const colorHex = getColorHex(randomRgb)
      document.writeln(`
        <div class="random-color-box" style="background-color: ${colorRgb}">
          <p>${colorHex}</p>
          <p>${colorRgb}</p>
        </div>
      `)
    }
    document.writeln('</div>')

    function getColorHex({ r, g, b }) {
      return `#${((r << 16) + (g << 8) + b).toString(16).padStart(6, '0')}`
    }

    function getColorRgb({ r, g, b }) {
      return `rgb(${r}, ${g}, ${b})`
    }

    function getRandomRgb() {
      const r = getRandom(0, 255)
      const g = getRandom(0, 255)
      const b = getRandom(0, 255)
      return { r, g, b }
    }

    function getRandom(m, n) {
      return Math.floor(Math.random() * (n - m + 1)) + m
    }
  </script>
</body>

</html>